package cn.fastloader.web.controller;

import cn.fastloader.util.FileInfoUtils;
import cn.fastloader.web.dao.TChunkInfoMapper;
import cn.fastloader.web.model.ApiResult;
import cn.fastloader.web.model.TChunkInfo;
import cn.fastloader.web.model.TFileInfo;
import cn.fastloader.web.model.TFileInfoVO;
import cn.fastloader.web.service.FileInfoService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.List;

/**
 * @author :yihui.He
 * @description :
 * @date :2021/1/23
 */
@RestController
@RequestMapping("/upload")
public class BigFileUploadController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private TChunkInfoMapper tChunkInfoMapper;

    @Value("${prop.upload-folder}")
    private String uploadFolder;

    @Resource
    private FileInfoService fileInfoService;

    @GetMapping("/check/file")
    public ApiResult checkExistedChunk(TChunkInfo  chunkInfo) {
        // 1.todo 检查参数是否合法
        TChunkInfo result = tChunkInfoMapper.getExistedChunk(chunkInfo);
        if (result != null) {
            Integer chunkNumber = result.getChunkNumber();
            if (chunkNumber.equals(result.getTotalChunks())) {
                // 已经上传完毕。
            }
            // todo  校验该chunk 文件是否存在。如果存在就设置chunkNumber
            setResponseMsg(HttpStatus.OK.value(), chunkNumber);

        }else {
            setResponseMsg(HttpStatus.OK.value(), null);
        }
        return ApiResult.success();
    }


    @PostMapping("/mergeFile")
    public String mergeFile(@RequestBody TFileInfoVO fileInfoVO){
        System.out.println("--------->合并文件！");
        String rlt = "FALURE";

        //前端组件参数转换为model对象
        // todo  设置状态，合并中。
        TFileInfo fileInfo = new TFileInfo();
        fileInfo.setFilename(fileInfoVO.getName());
        fileInfo.setIdentifier(fileInfoVO.getUniqueIdentifier());
        fileInfo.setId(fileInfoVO.getId());
        fileInfo.setTotalSize(fileInfoVO.getSize());
        fileInfo.setRefProjectId(fileInfoVO.getRefProjectId());

        //校验。 查询所有的info  检验信息是否存在。
        List<TChunkInfo> tChunkInfos = tChunkInfoMapper.selectAllChunckByMd5(fileInfo.getIdentifier());
        if (tChunkInfos.isEmpty() || tChunkInfos.size() != tChunkInfos.get(0).getTotalChunks()) {
            // 数量对不上，抛出异常。
        }
      // 判断上传的文件  是否全部都在文件下。如果存在就进行合并。

        //进行文件的合并操作
        String filename = fileInfo.getFilename();
        String file = uploadFolder + "/" + fileInfo.getIdentifier() + "/" + filename;
        String folder = uploadFolder + "/" + fileInfo.getIdentifier();
        // 自己的法进行合并。

        String fileSuccess = FileInfoUtils.merge(file, folder, filename);

        fileInfo.setLocation(file);

        //文件合并成功后，保存记录至数据库
        if("200".equals(fileSuccess)) {
            if(fileInfoService.addFileInfo(fileInfo) > 0) rlt = "SUCCESS";
        }

        //如果已经存在，则判断是否同一个项目，同一个项目的不用新增记录，否则新增
        if("300".equals(fileSuccess)) {
            List<TFileInfo> tfList = fileInfoService.selectFileByParams(fileInfo);
            if(tfList != null) {
                if(tfList.size() == 0 || (tfList.size() > 0 && !fileInfo.getRefProjectId().equals(tfList.get(0).getRefProjectId()))) {
                    if(fileInfoService.addFileInfo(fileInfo) > 0) rlt = "SUCCESS";
                }
            }
        }

        return rlt;
    }

    private void setResponseMsg(int status, Object message) {
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(status);
        try(ServletOutputStream outputStream = response.getOutputStream()) {
            if (message != null) {
                outputStream.write(JSONObject.toJSONBytes(message));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }
    }



}
